#include "predictor.h"
#include "randomgenerator.h"
#include <iostream>
#include <QFile>
#include <QtCore>

/*
** This is the Predictor constructor which takes in the time variable to be set for the prediction to last
**
*/
Predictor::Predictor(qint16 timeLimit) {
    qDebug() << "Predictor has started!!!";
    startTime = QTime::currentTime();
    stopTime = startTime.addSecs(timeLimit*60);
    qDebug() << "Timer should stop in "<< timeLimit <<" minutes";
}

/*
** This function is for starting the prediction for the given stockCode.
*/
void Predictor::startPrediction()
{
    qDebug() << "Start prediction";
    predictionMethod();
}

/*
** This is the actual method for prediction
*/
void Predictor::predictionMethod()
{
    QHash<QString, QString> dataToBePredicted  = this->getLastDataPredicted();
    QDateTime time = QDateTime::fromString(dataToBePredicted.value("time"), "yyyy-MM-dd HH:mm:ss");
    qDebug() << "Starting the Predictor Method and highest value = " << this->getHighestStockValue();
    qDebug() << "Last time the stock was having a value = " << time.time();
    qDebug() << "Closing time of market = " << QTime::fromString(MARKET_CLOSE, CLOCK_FORMAT);

    if (time.time() >= QTime::fromString(MARKET_CLOSE, CLOCK_FORMAT)) {
        qDebug() << "Timer has stopped, Hurray!";
    }
    else {
        QHash<QString, QString> predictedData;
        predictedData.insert("stockCode", dataToBePredicted.value("stockCode"));
        qsrand((uint)dataToBePredicted.value("price").toInt());
        QString value = this->getHighestStockValue();

        double price = QString::number(((rand() % ((int)value.toDouble())) + 0)).toDouble();
        double decimals = QString::number(((rand() % (STOCK_PRICE_DEC_MAX)) + 0)).toDouble();
        double randomStockPrice = (double)price + (double)(decimals / 10); //division will produce decimal most likely
        QVariant var1(randomStockPrice);
        predictedData.insert("price", var1.toString());

        time = time.addSecs(60*5);
        QString timeData =  time.date().toString(DATE_FORMAT) + " " + time.time().toString(CLOCK_FORMAT);
        predictedData.insert("time", timeData);
        this->setLastDataPredicted(predictedData);
        emit drawNextLineToUi(predictedData);
    }
}

void Predictor::setHighestStockValue(QString value) {
    STOCK_PRICE_MAX = value;
}

QString Predictor::getHighestStockValue() {
    return STOCK_PRICE_MAX;
}


void Predictor::setLastDataPredicted(QHash<QString, QString> predictedData) {
    lastDataPredicted = predictedData;
}

QHash<QString, QString> Predictor::getLastDataPredicted() {
    return lastDataPredicted;
}

/*
** Public function to get the startTime
*/
QTime Predictor::getStartTime() {
    return startTime;
}

/*
** Public function to get the endime
*/
QTime Predictor::getStopTime() {
    return stopTime;
}
